<?php

namespace GroupBuying;

use C\L\WebController;
use C\M\GroupBuyingGoods;

class GoodsController extends WebController
{
  /**
   * 列表、搜索接口
   **/
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $title       = $this->request->getQuery('title', 'string', null);

        $columns = ['id', 'thumbnail', 'title', 'description', 'price', 'stock', 'status', 'other_info'];

        $conditions = '1 = 1';
        $bind = [];

        $conditions .= ' AND status IN ({status:array})';
        $bind['status'] = ['on_sale', 'pre_sale'];

        if ($title) {
            $conditions .= ' AND title LIKE :title:';
            $bind['title'] = '%' . $title . '%';
        }

        $params =  [
        'conditions' => $conditions,
        'bind'       => $bind,
        'columns'    => $columns,
        'order'      => 'sort ASC, id DESC',
        ];
        $pagination = $this->paginate(GroupBuyingGoods::class, $currentPage, $perPage, $params);

        $offset = ($currentPage - 1) * $perPage;
        $params['limit'] = [$perPage, $offset];
        $items = GroupBuyingGoods::find($params);

      // 整理结构
        $items = array_map(
            function ($item) {
                $item['other_info'] = json_decode($item['other_info'], true);
                return $item;
            },
            $items->toArray()
        );

        $this->success(compact('pagination', 'items'));
    }

  /**
   * 详情接口
   **/
    public function showAction()
    {
        $id = $this->request->getQuery('id', 'int', 0);

        $goods = GroupBuyingGoods::findFirst([
        'conditions' => 'id = :id: AND status IN ({status:array})',
        'bind' => [
        'id'     => $id,
        'status' => ['on_sale', 'pre_sale'],
        ]
        ]);
        if (!$goods) {
            return $this->error('未找到该商品');
        }

        $goods->other_info = json_decode($goods->other_info, true);

        $goods
        ? $this->success($goods)
        : $this->error();
    }
}
